package com.koo.modules.base.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.koo.common.exception.RRException;
import com.koo.common.utils.MyStrUtil;
import com.koo.common.utils.UserUtils;
import com.koo.modules.base.dao.BaseStoreConfigDao;
import com.koo.modules.base.entity.BaseStoreConfigEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @version V1.0
 * @Description：
 * @Author: charlin
 * @Date: 2023/1/4 14:15
 */
@Component
public class ServiceUtil {

    public static final Map<String, Boolean> STATUS_CACHE_MAP = new ConcurrentHashMap<>(100);
    public static final Integer MAX_ONE_DOWNLOAD_COUNT = 1000;

    private static ServiceUtil serviceUtil;

    @PostConstruct
    public void init() {
        serviceUtil = this;
    }

    @Autowired
    private BaseStoreConfigDao baseStoreConfigDao;

    /**
     * 获得门店数据迁移状态
     */
    public static BaseStoreConfigEntity getStoreConfig() {
        LambdaQueryWrapper<BaseStoreConfigEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseStoreConfigEntity::getStoreId, UserUtils.getStoreId());
        return serviceUtil.baseStoreConfigDao.selectOne(wrapper);
    }

    public static BaseStoreConfigEntity getSysConfigBeanByStoreCode() {
        LambdaQueryWrapper<BaseStoreConfigEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseStoreConfigEntity::getStoreCode, UserUtils.getStoreCode());
        return serviceUtil.baseStoreConfigDao.selectOne(wrapper);
    }

    public static boolean isDataMigrated() {
        BaseStoreConfigEntity sysConfig = getStoreConfig();
        if (Objects.equals(sysConfig.getMigrateStockStatus(), 1) && Objects.equals(sysConfig.getMigrateMemberStatus(), 1) && Objects.equals(sysConfig.getMigratePriceStatus(), 1)) {
            return true;
        }
        return false;
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public static void updateDBConfigClickStatus(String clickColumn, Integer status, String downloadStatusKey) {
        STATUS_CACHE_MAP.put(downloadStatusKey, Objects.equals(status, 1));
        try {
            setProperty(clickColumn, status);
        } catch (Exception e) {
            throw new RRException("设置值失败", e);
        }
    }



    public static boolean getCacheStatus(String downloadStatusKey) {
        return MyStrUtil.isEmpty(STATUS_CACHE_MAP.get(downloadStatusKey)) ? false : STATUS_CACHE_MAP.get(downloadStatusKey);
    }


    public static Object getProperty(String key) {
        BaseStoreConfigEntity sysConfig = getSysConfigBeanByStoreCode();
        Method method = null;
        Object invoke = null;
        try {
            method = sysConfig.getClass().getMethod("get" + upperKey(key));
            invoke = method.invoke(sysConfig);
        } catch (NoSuchMethodException e) {
            throw new RRException("执行方法错误，找不到传入的配置key", e);
        } catch (SecurityException e) {
            throw new RRException("获取属性异常", e);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return invoke;
    }

    public static void setProperty(String key, Object value) {
        BaseStoreConfigEntity sysConfig = getSysConfigBeanByStoreCode();
        Method method = null;
        Class cls = null;
        if (value instanceof String) {
            cls = String.class;
        } else if (value instanceof Integer) {
            cls = Integer.class;
        } else if (value instanceof BigDecimal) {
            cls = BigDecimal.class;
        } else if (value instanceof Date) {
            cls = Date.class;
        } else if (value instanceof Double) {
            cls = Double.class;
        } else {
            cls = Object.class;
        }
        try {
            method = sysConfig.getClass().getMethod("set" + upperKey(key), cls);
            method.invoke(sysConfig, value);
            serviceUtil.baseStoreConfigDao.updateById(sysConfig);
        } catch (NoSuchMethodException e) {
            throw new RRException("执行方法错误，找不到传入的配置key:" + value.getClass(), e);
        } catch (SecurityException e) {
            throw new RRException("获取属性异常", e);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static String upperKey(String key) {
        return key.substring(0, 1).toUpperCase() + key.substring(1, key.length());
    }

    /**
     * 获得int类型结果
     *
     * @param key
     * @return
     */
    public static Integer getIntProperty(String key) {
        return Integer.parseInt(getStringProperty(key));
    }

    /**
     * 获取String类型结果
     *
     * @param key
     * @return
     */
    public static String getStringProperty(String key) {
        Object property = getProperty(key);
        if (property == null) {
            return "0";
        }
        return property.toString();
    }
}
